package org.streamerstudio.samples;

import java.awt.BorderLayout;
import java.awt.Frame;

import org.eclipse.core.runtime.Status;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.swt.SWT;
import org.eclipse.swt.awt.SWT_AWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.gstreamer.Element;
import org.gstreamer.ElementFactory;
import org.gstreamer.Pipeline;
import org.gstreamer.State;
import org.gstreamer.swing.VideoComponent;

/**
 * This class controls all aspects of the application's execution
 */
public class Application implements IApplication {

	Pipeline pipe;
	
	/* (non-Javadoc)
	 * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
	 */
	public Object start(IApplicationContext context) throws Exception {
        // Quartz is abysmally slow at scaling video for some reason, so turn it off.
        System.setProperty("apple.awt.graphics.UseQuartz", "false");
        
        // Gst.init("SWTOverlayPlayer", new String[] {});
        
        /*ElementFactory.make("gdiscreencapsrc", "source");
        videosrc.set("cursor", "true");
        videosrc.set("width", "600");
        videosrc.set("height", "400");*/
        
        Element videosrc = ElementFactory.make("videotestsrc", "source");
        
        Display display = new Display();
		Shell shell = new Shell(display);
		shell.setSize(640, 480);
		shell.setLayout(new FillLayout());

		shell.setText("SWT Video Test");
		Composite composite = new Composite(shell, SWT.EMBEDDED | SWT.NO_BACKGROUND);
		final VideoComponent component = new VideoComponent();
		component.getElement().setName("video");
		component.setKeepAspect(true);
        
		pipe = new Pipeline("pipeline");
        Element videosink = component.getElement();
        pipe.addMany(videosrc, videosink);
        Element.linkMany(videosrc, videosink);

        Frame frame = SWT_AWT.new_Frame(composite);
        frame.add(component, BorderLayout.CENTER);
        
        // Start the pipeline processing
        pipe.setState(State.PLAYING);
        
        shell.open();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		pipe.setState(State.PAUSED);
		pipe.setState(State.NULL);
		display.dispose();
        
        return Status.OK;
    }

	/* (non-Javadoc)
	 * @see org.eclipse.equinox.app.IApplication#stop()
	 */
	public void stop() {
		// nothing to do
	}
}
